package com.atguigu.gmall.order.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.nacos.common.utils.StringUtils;
import com.atguigu.gmall.cart.client.CartFeignClient;
import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.util.AuthContextHolder;
import com.atguigu.gmall.model.cart.CartInfo;
import com.atguigu.gmall.model.order.OrderDetail;
import com.atguigu.gmall.model.order.OrderInfo;
import com.atguigu.gmall.model.user.UserAddress;
import com.atguigu.gmall.order.service.OrderService;
import com.atguigu.gmall.product.client.ProductFeignClient;
import com.atguigu.gmall.user.client.UserFeignClient;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.ApiOperation;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

@RestController
@RequestMapping("api/order")
public class OrderApiController {

    @Autowired
    private UserFeignClient userFeignClient;

    @Autowired
    private CartFeignClient cartFeignClient;

    @Autowired
    private OrderService orderService;

    @Autowired
    private ProductFeignClient productFeignClient;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private ThreadPoolExecutor threadPoolExecutor;

    //auth 加权限必须登录
    @ApiOperation("确认订单")
    @GetMapping("/auth/trade")
    public Result<Map<String,Object>> trade(HttpServletRequest request){
        //获取到用户id
        String userId = AuthContextHolder.getUserId(request);
        //获取用户地址
        List<UserAddress> userAddressList  = userFeignClient.findUserAddressListByUserId(userId);
        // 渲染送货清单
        // 先得到用户想要购买的商品！
        List<CartInfo> cartCheckedList = cartFeignClient.getCartCheckedList(userId);
        // 声明一个集合来存储订单明细
        List<OrderDetail> detailArrayList = cartCheckedList.stream().map(cartInfo -> {
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setSkuId(cartInfo.getSkuId());
            orderDetail.setSkuName(cartInfo.getSkuName());
            orderDetail.setSkuNum(cartInfo.getSkuNum());
            orderDetail.setImgUrl(cartInfo.getImgUrl());
            orderDetail.setOrderPrice(cartInfo.getCartPrice());
            return orderDetail;
        }).collect(Collectors.toList());
        // 计算总金额
        OrderInfo orderInfo = new OrderInfo();
        //把信息储放到订单明细中
        orderInfo.setOrderDetailList(detailArrayList);
        orderInfo.sumTotalAmount();

        Map<String, Object> result = new HashMap<>();
        result.put("userAddressList", userAddressList);
        result.put("detailArrayList", detailArrayList);
        // 保存总金额
        result.put("totalNum", detailArrayList.size());
        result.put("totalAmount", orderInfo.getTotalAmount());
//        订单流水号
        result.put("tradeNo",orderService.getTradeNo(userId));

        return Result.ok(result);
    }

    /**
     * 提高订单  需要流水号v   不加锁的原因是缓解系统压力 ，并发大加锁会很慢，导致系统卡死
     */
    @PostMapping("/auth/submitOrder")
    public Result submitOrder(@RequestBody OrderInfo orderInfo, HttpServletRequest request) {
        // 获取到用户Id
        String userId = AuthContextHolder.getUserId(request);
        orderInfo.setUserId(Long.parseLong(userId));
        //获取页面的流水号
        String tradeNo = request.getParameter("tradeNo");
        //调用比较方法
        Boolean result = orderService.checkTradeNo(tradeNo, userId);
        if (!result) {
           return Result.fail().message("不能回退无刷新提交订单！");
        }
        //每个商品都要判断
        List<OrderDetail> orderDetailList = orderInfo.getOrderDetailList();
        //定义一个返回库存的集合
        List<CompletableFuture>  futureList=new ArrayList<>();
        //返回信息集合
        List<String> errorList=new ArrayList<>();
        if (!CollectionUtils.isEmpty(orderDetailList)){
            for (OrderDetail orderDetail : orderDetailList) {
                //无参数无返回值
                CompletableFuture<Void> stockCompletableFuture = CompletableFuture.runAsync(() -> {
                    //调用验证库存方法
                    Boolean flag = orderService.checkStock(orderDetail.getSkuId(), orderDetail.getSkuNum());
                    if (!flag) {
                        errorList.add((orderDetail.getSkuName() + ":\t 没有足够的库存!"));
                    }
                },threadPoolExecutor);
                //添加验证库存
                futureList.add(stockCompletableFuture);

                CompletableFuture<Void> priceCompletableFuture = CompletableFuture.runAsync(() -> {
                    //验证价格
                    BigDecimal skuPrice = productFeignClient.getSkuPrice(orderDetail.getSkuId());
                    if (orderDetail.getOrderPrice().compareTo(skuPrice) != 0) {
                        //重新查询价格
                        //设置最新的价格
                        List<CartInfo> cartCheckedList = cartFeignClient.getCartCheckedList(userId);
                        //写入缓存  hvals key
                        cartCheckedList.forEach(cartInfo -> {
                            redisTemplate.opsForHash().put(RedisConst.USER_KEY_PREFIX + userId + RedisConst.USER_CART_KEY_SUFFIX, cartInfo.getSkuId().toString(), cartInfo);
                        });
                        //价格
                        BigDecimal orderPrice = orderDetail.getOrderPrice();
                        BigDecimal amount = orderPrice.subtract(skuPrice);
                        String msg = "";
                        if (amount.intValue() > 0) {
                            msg = "比原来降价：" + amount;
                        } else {
                            msg = "比原来上涨：" + amount.abs();   //取绝对值
                        }
                        errorList.add(orderDetail.getSkuName() + "价格有变动！" + msg);
                    }
                },threadPoolExecutor);
                //验证价格
                futureList.add(priceCompletableFuture);
            }
            //合并线程
            CompletableFuture.allOf(futureList.toArray(new CompletableFuture[futureList.size()])).join();
            if (errorList.size()>0){
                return Result.fail().message(StringUtils.join(errorList, ","));
            }
        }
        orderService.delTradeNo(userId);//成功下单后，删除缓存流水号
        // 验证通过，保存订单！
        Long orderId = orderService.saveOrderInfo(orderInfo);
        return Result.ok(orderId);
    }


    @ApiOperation("显示我得订单管理")
    @GetMapping("/auth/{page}/{limit}")
    public Result index(@PathVariable Long page,
                        @PathVariable Long limit,
                        HttpServletRequest request){
        Page<OrderInfo> pageParam  = new Page<>(page,limit);
        IPage<OrderInfo> pageModel =orderService.getPage(pageParam,AuthContextHolder.getUserId(request));
        return  Result.ok(pageModel);
    }

    /**
     * 内部调用获取订单
     * @param orderId
     * @return
     */
    @GetMapping("inner/getOrderInfo/{orderId}")
    public OrderInfo getOrderInfo(@PathVariable(value = "orderId") Long orderId){
        return orderService.getOrderInfo(orderId);
    }

    /**
     * 拆单业务
     * @param request
     * @return
     */
    @PostMapping("orderSplit")
    public String orderSplit(HttpServletRequest request){
        String orderId = request.getParameter("orderId");//订单系统的订单ID
        String wareSkuMap = request.getParameter("wareSkuMap");//仓库编号与商品的对照关系
        //拆单：获取到的子订单集合
        List<OrderInfo> subOrderInfoList = orderService.orderSplit(Long.parseLong(orderId), wareSkuMap);
        // 声明一个存储map的集合
        List<Map> mapArrayList = new ArrayList<>();
        // 生成子订单集合
        List<Map> mapArrays = subOrderInfoList.stream().map(orderInfo -> {
            Map map = orderService.initWareOrder(orderInfo);
            //添加到集合
//            由于数据是一对多
            mapArrayList.add(map);
            return map;
        }).collect(Collectors.toList());
//        for (OrderInfo orderInfo : subOrderInfoList) {
//            Map map = orderService.initWareOrder(orderInfo);
////            //添加到集合
//////            由于数据是一对多
//            mapArrayList.add(map);
//        }
        return JSON.toJSONString(mapArrays);
    }

         /* 秒杀提交订单，秒杀订单不需要做前置判断，直接下单
     * @param orderInfo
     * @return
         */
    @PostMapping("inner/seckill/submitOrder")
    public Long submitOrder(@RequestBody OrderInfo orderInfo) {
        Long orderId = orderService.saveOrderInfo(orderInfo);
        return orderId;
    }

}
